package org.yang.jspgenerator.controller;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.yang.jspgenerator.code.Code;
import org.yang.jspgenerator.common.Lay;
import org.yang.jspgenerator.service.GeneratorService;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.zip.ZipOutputStream;

/**
 * @author shichenyang
 */
@Controller
@RequestMapping("/gen")
public class GenController {
    @Autowired
    private GeneratorService service;
    @Autowired
    private Code code;
    @RequestMapping
    public String index(){
        return "generator/index.html";
    }

    @RequestMapping("/list")
    @ResponseBody
    public Lay getList(String tableName, Integer page, Integer limit){
        return service.getByList(tableName,page,limit);
    }

    @RequestMapping("/code")
    public void code(String [] tableNames, HttpServletResponse response) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        code.code(Arrays.asList(tableNames),zip);
        IOUtils.closeQuietly(zip);

        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"bohua.zip\"");
        response.addHeader("Content-Length", "" + outputStream.toByteArray().length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IOUtils.write(outputStream.toByteArray(), response.getOutputStream());
    }
}
